package cn.tedu.csmall520.order.webapi.controller;

import cn.tedu.csmall520.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall520.commons.pojo.order.dto.OrderAddDTO;
import cn.tedu.csmall520.commons.pojo.order.entity.Order;
import cn.tedu.csmall520.commons.restful.JsonPage;
import cn.tedu.csmall520.commons.restful.JsonResult;
import cn.tedu.csmall520.commons.restful.ResponseCode;
import cn.tedu.csmall520.order.service.IOrderService;
import cn.tedu.csmall520.order.webapi.service.impl.OrderServiceImpl;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.rpc.RpcException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.json.Json;

@RestController
@Slf4j
@Api(tags = "订单管理模块")
@RequestMapping("/base/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;


    @PostMapping("/add-new")
    @ApiOperation("新增订单")
    @SentinelResource(value = "新增订单",blockHandler = "blockError",fallback = "fallError")
    public JsonResult addNew (OrderAddDTO orderAddDTO){
        log.debug("开始处理新增订单的请求");
        try {
            orderService.addNew(orderAddDTO);
        }catch (RpcException e){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"hhh");
        }
        return JsonResult.ok("新增成功");
    }

    public JsonResult blockError(OrderAddDTO orderAddDTO, BlockException e){
        return JsonResult.failed(ResponseCode.INTERNAL_SERVER_ERROR,"服务器忙，稍后尝试");
    }

    public JsonResult fallError(OrderAddDTO orderAddDTO,Throwable throwable){
        throwable.printStackTrace();
        return JsonResult.failed(ResponseCode.INTERNAL_SERVER_ERROR,"方法异常，服务降级");
    }

    @GetMapping("/page")
    @ApiOperation("分页查询所有订单")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "页码",name = "page",example = "1"),
            @ApiImplicitParam(value = "每页条数",name = "pageSize",example = "5"),
    })
    public JsonResult<JsonPage<Order>> pageOrder (Integer page, Integer pageSize) {
        JsonPage<Order> jsonPage = orderService.getAllOrderByPage(page,pageSize);
        return JsonResult.ok("查询完成",jsonPage);
    }


}
